package evi.com.evi.login;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.bouncycastle.jcajce.provider.symmetric.TEA;

import java.io.IOException;

import cn.jpush.android.api.JPushInterface;
import evi.com.evi.R;
import evi.com.evi.activity.GoodsAddActivity;
import evi.com.evi.activity.HomeActivity;
import evi.com.evi.activity.WebviewActivity;
import evi.com.evi.application.MyApplication;
import evi.com.evi.utils.AppUtils;
import evi.com.evi.utils.ConnectUtil;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.RSAPublicUtil;
import evi.com.evi.utils.RegexUtils;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.ScreenUtils;
import evi.com.evi.utils.ToastUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends Activity implements OnClickListener {
    private static final String TAG = "TAG";

    private TextView login_sure;
    private TextView login_code;
    private TextView login_forget;

    private TextView tv_login_url;

    private EditText et_username;
    private EditText et_pwd;
    private String username = ""; // 存储用户名
    private String pwd = ""; // 存储密码
    private MyHandler myHandler;
    private final int RequestSuccess = 0;// 请求成功\

    private OkHttpClient client;
    private JSONUtils jsonUtils;

    private Dialog dialog;


    class MyHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RequestSuccess:// 所有请求都成功跳转到主页面
//				startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                    finish();
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.getInstance().addActivity(this);
        ScreenUtils.setTranStatus(this, true, Color.parseColor("#FF6600"));
        setContentView(R.layout.activity_login);
        myHandler = new MyHandler();
        initViewAndData();
    }

    /**
     * 初始化
     */
    private void initViewAndData() {
        et_username = (EditText) findViewById(R.id.login_username);
        et_pwd = (EditText) findViewById(R.id.login_pwd);

        // 点击事件
        login_sure = (TextView) findViewById(R.id.login_sure);
        login_sure.setOnClickListener(this); // 点击登录
        login_code = (TextView) findViewById(R.id.login_code);
        login_code.setOnClickListener(this); // 动态码登录
        login_forget = (TextView) findViewById(R.id.login_forget);
        login_forget.setOnClickListener(this); // 忘记密码

        tv_login_url = (TextView) findViewById(R.id.tv_login_url);
        tv_login_url.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tv_login_url.setOnClickListener(this);

        client = new OkHttpClient();
        jsonUtils = new JSONUtils();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_sure: // 登录


                username = et_username.getText().toString().trim();
                pwd = et_pwd.getText().toString().trim();
                if (!RegexUtils.isRegex(username, RegexUtils.RX_Mobile)) {
                    ToastUtils.showMsg(LoginActivity.this, "请输入手机号");
                } else {

                    getRSA();

                }
                break;
            case R.id.login_code:        //动态码登录
                startActivity(new Intent(LoginActivity.this, LoginByCodeActivity.class));
                break;
            case R.id.login_forget:        //忘记密码
                startActivity(new Intent(LoginActivity.this, ForgetPwdActivity.class));
                break;

            case R.id.tv_login_url:
                //点击用户协议触发事件
                startActivity(new Intent(this, WebviewActivity.class));
                break;
            default:
                break;
        }
    }

    private String modulus;
    private String exponent;

    /**
     * 获取RSA
     */

    private void getRSA() {
        dialog = AppUtils.getLoadingDialog(this, "提示", "正在登录，请稍后");
        dialog.show();
        String tag = "?tag=1";
        Request request = new Request.Builder()
                .url(ContentUtils.RSA_url + tag)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(LoginActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        modulus = jsonObject.getJSONObject("data").getString("modulus");
                        exponent = jsonObject.getJSONObject("data").getString("exponent");
                        getTokenSalt();
                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
            }
        });


    }

    /**
     * 获取token和salt
     */
    private String salt;
    private String token;

    private void getTokenSalt() {
        Request request = new Request.Builder()
                .url(ContentUtils.tokenSalt_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(LoginActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        salt = jsonObject.getJSONObject("data").getString("salt");
                        token = jsonObject.getJSONObject("data").getString("token");
                        SPUtil.setString(LoginActivity.this, "token", token);
                        login();
                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
            }
        });

    }

    private String phoneNo;
    private String password;
    private String password_real;

    /**
     * 登录方法
     */

    private void login() {

        phoneNo = et_username.getText().toString();
        password = et_pwd.getText().toString();
        password_real = RSAPublicUtil.publicEncryptString(modulus, exponent, salt + password);
        String login = "?phoneNo=" + phoneNo + "&password=" + password_real;
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.login_url + login)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(LoginActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                        finish();
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });
    }


    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().deleteActivity(this);
    }
}
